from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity
from models import User, db
from utils import hash_password, verify_password, format_response
import traceback

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        print(f"登录请求数据: {data}")
        
        username = data.get('username')
        password = data.get('password')
        
        print(f"用户名: {username}, 密码: {password}")
        
        if not username or not password:
            return jsonify(format_response(message="用户名和密码不能为空", code=400)), 400
        
        user = User.query.filter_by(username=username).first()
        print(f"查询到的用户: {user}")
        
        if not user:
            print("用户不存在")
            return jsonify(format_response(message="用户名或密码错误", code=401)), 401
        
        print(f"用户密码哈希: {user.password}")
        password_valid = verify_password(password, user.password)
        print(f"密码验证结果: {password_valid}")
        
        if not password_valid:
            print("密码验证失败")
            return jsonify(format_response(message="用户名或密码错误", code=401)), 401
        
        # 创建JWT token - 将用户ID转换为字符串
        access_token = create_access_token(identity=str(user.id))
        print(f"生成的token: {access_token}")
        
        user_dict = user.to_dict()
        print(f"用户信息: {user_dict}")
        
        response_data = {
            'token': access_token,
            'token_type': 'bearer',
            'user': user_dict
        }
        
        print(f"响应数据: {response_data}")
        return jsonify(format_response(response_data))
        
    except Exception as e:
        print(f"登录过程中出现错误: {str(e)}")
        print(f"错误详情: {traceback.format_exc()}")
        return jsonify(format_response(message=str(e), code=500)), 500

@auth_bp.route('/register', methods=['POST'])
@jwt_required()
def register():
    """用户注册 - 只允许管理员和教师注册学生账号"""
    try:
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        # 检查权限：只有管理员和教师可以注册学生
        if current_user.role not in ['admin', 'teacher']:
            return jsonify(format_response(message="权限不足，只有管理员和教师可以注册学生账号", code=403)), 403
        
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        name = data.get('name', '')
        email = data.get('email', '')
        role = data.get('role', 'student')  # 默认注册学生
        
        # 限制只能注册学生账号
        if role != 'student':
            return jsonify(format_response(message="只能注册学生账号", code=400)), 400
        
        if not username or not password or not name:
            return jsonify(format_response(message="用户名、密码和姓名不能为空", code=400)), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            return jsonify(format_response(message="用户名已存在", code=400)), 400
        
        # 创建新学生用户
        hashed_password = hash_password(password)
        new_user = User(
            username=username, 
            password=hashed_password, 
            name=name,
            email=email,
            role=role
        )
        db.session.add(new_user)
        db.session.commit()
        
        return jsonify(format_response(new_user.to_dict(), "学生账号注册成功"))
        
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@auth_bp.route('/register-admin', methods=['POST'])
def register_admin():
    """注册管理员账号 - 无需登录"""
    try:
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        name = data.get('name', '')
        email = data.get('email', '')
        
        if not username or not password:
            return jsonify(format_response(message="用户名和密码不能为空", code=400)), 400
        
        # 检查用户名是否已存在
        if User.query.filter_by(username=username).first():
            return jsonify(format_response(message="用户名已存在", code=400)), 400
        
        # 创建新管理员用户
        hashed_password = hash_password(password)
        new_user = User(
            username=username, 
            password=hashed_password, 
            name=name,
            email=email,
            role='admin'
        )
        db.session.add(new_user)
        db.session.commit()
        
        return jsonify(format_response(new_user.to_dict(), "管理员账号注册成功"))
        
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@auth_bp.route('/register-batch', methods=['POST'])
@jwt_required()
def register_batch():
    """批量注册学生账号"""
    try:
        # 获取当前用户
        current_user_id = get_jwt_identity()
        current_user = User.query.get(current_user_id)
        
        if not current_user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        # 检查权限：只有管理员和教师可以批量注册学生
        if current_user.role not in ['admin', 'teacher']:
            return jsonify(format_response(message="权限不足，只有管理员和教师可以批量注册学生账号", code=403)), 403
        
        data = request.get_json()
        students = data.get('students', [])
        
        if not students or not isinstance(students, list):
            return jsonify(format_response(message="学生数据格式错误", code=400)), 400
        
        if len(students) > 100:  # 限制批量注册数量
            return jsonify(format_response(message="批量注册数量不能超过100个", code=400)), 400
        
        success_count = 0
        failed_students = []
        
        for student_data in students:
            try:
                username = student_data.get('username')
                password = student_data.get('password', 'student123')  # 默认密码
                name = student_data.get('name', '')
                email = student_data.get('email', '')
                
                if not username or not name:
                    failed_students.append({
                        'username': username,
                        'name': name,
                        'error': '用户名和姓名不能为空'
                    })
                    continue
                
                # 检查用户名是否已存在
                if User.query.filter_by(username=username).first():
                    failed_students.append({
                        'username': username,
                        'name': name,
                        'error': '用户名已存在'
                    })
                    continue
                
                # 创建新学生用户
                hashed_password = hash_password(password)
                new_user = User(
                    username=username,
                    password=hashed_password,
                    name=name,
                    email=email,
                    role='student'
                )
                db.session.add(new_user)
                success_count += 1
                
            except Exception as e:
                failed_students.append({
                    'username': username if 'username' in locals() else 'unknown',
                    'name': name if 'name' in locals() else 'unknown',
                    'error': str(e)
                })
        
        db.session.commit()
        
        return jsonify(format_response({
            'success_count': success_count,
            'failed_count': len(failed_students),
            'failed_students': failed_students
        }, f"批量注册完成，成功{success_count}个，失败{len(failed_students)}个"))
        
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500

@auth_bp.route('/profile', methods=['GET'])
@jwt_required()
def get_profile():
    """获取用户信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        return jsonify(format_response(user.to_dict()))
        
    except Exception as e:
        return jsonify(format_response(message=str(e), code=500)), 500

@auth_bp.route('/change-password', methods=['POST'])
@jwt_required()
def change_password():
    """修改密码"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify(format_response(message="用户不存在", code=404)), 404
        
        data = request.get_json()
        old_password = data.get('old_password')
        new_password = data.get('new_password')
        
        if not old_password or not new_password:
            return jsonify(format_response(message="旧密码和新密码不能为空", code=400)), 400
        
        if not verify_password(old_password, user.password):
            return jsonify(format_response(message="旧密码错误", code=400)), 400
        
        user.password = hash_password(new_password)
        db.session.commit()
        
        return jsonify(format_response(message="密码修改成功"))
        
    except Exception as e:
        db.session.rollback()
        return jsonify(format_response(message=str(e), code=500)), 500
